package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.constant.MessageConstant;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.entity.Result;
import com.itheima.pojo.CheckGroup;
import com.itheima.pojo.CheckItem;
import com.itheima.service.CheckGroupService;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/checkgroup")
public class CheckGroupController {

    @Reference
    public CheckGroupService checkGroupService;

    @PostMapping("/findPage")
    public PageResult findPage(@RequestBody QueryPageBean queryPageBean) {
        return checkGroupService.findPage(queryPageBean);
    }

    @GetMapping("/findById")
    public Result findById(Integer id){
        CheckGroup checkGroup = checkGroupService.findById(id);
        if(checkGroup != null){
            return new Result(true,null,checkGroup);
        }
        return new Result(false,"查询出错");
    }



    @PostMapping("/edit")
    public Result update(@RequestBody CheckGroup checkGroup,Integer[] checkitemId){
        Integer result = checkGroupService.update(checkGroup,checkitemId);
        if (result == 1) {
            return new Result(true, "更新成功");
        }
        return new Result(false, "更新失败");
    }

    @GetMapping("/findCheckItemIdsByCheckGroupId")
    public Result findCheckItemIdsByCheckGroupId(Integer id){
        List<Integer> checkItemIds = checkGroupService.findCheckItemIdsByCheckGroupId(id);
        if (checkItemIds.size() > 0){
            return new Result(true,null,checkItemIds);
        }
        return new Result(false,"查询出错");
    }

    @GetMapping("/findAll")
    public Result findAll(){
        List<CheckGroup> all = checkGroupService.findAll();
        if (all.isEmpty()){
            return new Result(false,"查询出错");
        }
        return new Result(true,null,all);
    }


    @GetMapping("/delete")
    public Result delete(Integer id){
        try {
            Integer result = checkGroupService.delete(id);
            if(result == 1){
                return new Result(true,"删除成功");
            }else if(result == -1){
                return new Result(false,"检查组被套餐绑定，无法删除！");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new Result(false,"删除失败");
    }
    @RequestMapping("/add")
    public Result add(@RequestBody CheckGroup checkGroup, Integer[] checkitemIds) {
        try {
            checkGroupService.add(checkGroup, checkitemIds);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.ADD_CHECKGROUP_FAIL); //新增失败
        }
        return new Result(true, MessageConstant.ADD_CHECKGROUP_SUCCESS);//新增成功
    }
}
